package com.bm.specialvehiclefordispatcher.activity.mine;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.DisplayUtil;
import com.bm.corelibs.utils.SharedPreferencesUtil;
import com.bm.corelibs.utils.ViewHolder;
import com.bm.corelibs.views.LoadingSwipeMenuListView;
import com.bm.specialvehiclefordispatcher.R;
import com.bm.specialvehiclefordispatcher.activity.BaseActivity;
import com.bm.specialvehiclefordispatcher.activity.WebActivity;
import com.bm.specialvehiclefordispatcher.activity.order.OrderDetailActivity;
import com.bm.specialvehiclefordispatcher.bean.Announcement;
import com.bm.specialvehiclefordispatcher.bean.BaseData;
import com.bm.specialvehiclefordispatcher.bean.Message;
import com.bm.specialvehiclefordispatcher.constants.Constant;
import com.bm.specialvehiclefordispatcher.logics.AnnouncementManager;
import com.bm.specialvehiclefordispatcher.logics.MessageManager;
import com.bm.specialvehiclefordispatcher.views.CommonNavigationBar;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;

public class MessageAnnouncementActivity extends BaseActivity implements OnClickListener, OnRefreshListener2<SwipeMenuListView>, OnItemClickListener, OnMenuItemClickListener {

	private CommonNavigationBar navi;
	private LoadingSwipeMenuListView lv_ma;
	private TextView tv_message, tv_announce, tv_empty;
	private View selector;

	private List<Message> messages = new ArrayList<Message>();
	private List<Announcement> announcements = new ArrayList<Announcement>();
	private MaAdapter adapter = new MaAdapter();
	private MessageManager messageManager;
	private AnnouncementManager announcementManager;
	SharedPreferencesUtil sp;
	private int tempPosition;

	private Type type = Type.MESSAGES;

	public enum Type {
		MESSAGES, ANNOUNCEMENTS
	}

	int fromNoti;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_ma);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		navi = (CommonNavigationBar) findViewById(R.id.navi);
		lv_ma = (LoadingSwipeMenuListView) findViewById(R.id.lv_ma);
		tv_message = (TextView) findViewById(R.id.tv_message);
		tv_announce = (TextView) findViewById(R.id.tv_announce);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
		selector = (View) findViewById(R.id.v_divider);
	}

	@Override
	public void init() {
		sp = new SharedPreferencesUtil(mActivity, Constant.SpName);
		navi.setTitle(R.string.ma);
		navi.setListener(null);
		lv_ma.enablePullDownToRefresh();
		lv_ma.setAdapter(adapter);
		lv_ma.getRefreshableView().setMenuCreator(createMenu());
		messageManager = new MessageManager(sp.getStringByKey("id"));
		announcementManager = new AnnouncementManager(sp.getStringByKey("id"));
		messageManager.getFirst(getMessageListener());
		announcementManager.getFirst(getAnnouncementListener());
		tv_announce.post(new Runnable() {
			@Override
			public void run() {
				fromNoti = getIntent().getIntExtra("type", -1);
				if (fromNoti == 1) {
					type = Type.ANNOUNCEMENTS;
					selector.setTranslationX(selector.getWidth());
					tv_message.setTextColor(getResources().getColor(R.color.main_text));
					tv_announce.setTextColor(getResources().getColor(R.color.main));
				}
			}
		});
	}

	@Override
	public void addListeners() {
		tv_message.setOnClickListener(this);
		tv_announce.setOnClickListener(this);
		lv_ma.setOnRefreshListener(this);
		lv_ma.setOnItemClickListener(this);
		lv_ma.getRefreshableView().setOnMenuItemClickListener(this);
	}

	private Runnable refreshCompleted = new Runnable() {
		@Override
		public void run() {
			lv_ma.OnLoadingFinished();
			lv_ma.onRefreshComplete();
		}
	};

	private SwipeMenuCreator createMenu() {
		return new SwipeMenuCreator() {
			@Override
			public void create(SwipeMenu menu) {
				SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
				openItem.setBackground(R.color.main_red);
				openItem.setWidth(DisplayUtil.dip2px(mActivity, 90));
				openItem.setTitle(R.string.action_delete);
				openItem.setTitleSize(18);
				openItem.setTitleColor(Color.WHITE);
				menu.addMenuItem(openItem);
			}
		};
	}

	private NListener<BaseData> getMessageListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				mHandler.post(refreshCompleted);
				if (data.status == Constant.STATUS_OK) {
					if (data.data.msgs != null) {
						if (data.data.msgs.size() <= 0) {
							// tv_empty.setVisibility(View.VISIBLE);
						} else {
							tv_empty.setVisibility(View.GONE);
							messages.addAll(data.data.msgs);
							adapter.notifyDataSetChanged();
						}
					}
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
				lv_ma.disableLoading();
			}
		};
	}

	private NListener<BaseData> getAnnouncementListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				mHandler.post(refreshCompleted);
				if (data.status == Constant.STATUS_OK) {
					if (data.data.announcements != null) {
						if (data.data.announcements.size() <= 0) {
							// tv_empty.setVisibility(View.VISIBLE);
						} else {
							tv_empty.setVisibility(View.GONE);
							announcements.addAll(data.data.announcements);
							adapter.notifyDataSetChanged();
						}
					}
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
				lv_ma.disableLoading();
			}
		};
	}

	class MaAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			switch (type) {
			case MESSAGES:
				return messages == null ? 0 : messages.size();

			case ANNOUNCEMENTS:
				return announcements == null ? 0 : announcements.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			switch (type) {
			case MESSAGES:
				return messages.get(position);

			case ANNOUNCEMENTS:
				return announcements.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_ma, null);

			TextView tv_message_name = ViewHolder.get(convertView, R.id.tv_message_name);
			TextView tv_message_time = ViewHolder.get(convertView, R.id.tv_message_time);
			TextView tv_message_content = ViewHolder.get(convertView, R.id.tv_message_content);

			switch (type) {
			case MESSAGES:
				Message message = messages.get(position);
				tv_message_name.setText(message.msgName);
				tv_message_time.setText(message.sentDate);
				tv_message_content.setText(message.content);
				break;

			case ANNOUNCEMENTS:
				Announcement announcement = announcements.get(position);
				tv_message_name.setText(announcement.msgName);
				tv_message_time.setText(announcement.sentDate);
				tv_message_content.setText(announcement.content);
				break;
			}

			return convertView;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_message:
			type = Type.MESSAGES;
			adapter.notifyDataSetChanged();
			selector.setTranslationX(0);
			tv_message.setTextColor(getResources().getColor(R.color.main));
			tv_announce.setTextColor(getResources().getColor(R.color.main_text));
			break;

		case R.id.tv_announce:
			type = Type.ANNOUNCEMENTS;
			adapter.notifyDataSetChanged();
			selector.setTranslationX(selector.getWidth());
			tv_message.setTextColor(getResources().getColor(R.color.main_text));
			tv_announce.setTextColor(getResources().getColor(R.color.main));
			break;
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<SwipeMenuListView> refreshView) {
		switch (type) {
		case MESSAGES:
			messages.clear();
			messageManager.getFirst(getMessageListener());
			break;

		case ANNOUNCEMENTS:
			announcements.clear();
			announcementManager.getFirst(getAnnouncementListener());
			break;
		}
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<SwipeMenuListView> refreshView) {
		switch (type) {
		case MESSAGES:
			messageManager.getNext(getMessageListener());
			break;

		case ANNOUNCEMENTS:
			announcementManager.getNext(getAnnouncementListener());
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Object object = parent.getAdapter().getItem(position);
		Intent intent;
		switch (type) {
		case MESSAGES:
			Message message = (Message) object;
			switch (message.type) {
			// 车辆
			case 0:
				break;
			// 订单
			case 1:
				intent = new Intent(mActivity, OrderDetailActivity.class);
				intent.putExtra(OrderDetailActivity.ORDER_ID, message.typeId);
				startActivity(intent);
				break;

			default:
				break;
			}
			break;

		case ANNOUNCEMENTS:
			Announcement announcement = (Announcement) object;
			intent = new Intent(mActivity, WebActivity.class);
			intent.putExtra("url", announcement.htmlSrc);
			startActivity(intent);
			break;
		}
	}

	@Override
	public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
		this.tempPosition = position;
		switch (type) {
		case MESSAGES:
			loadingDialog.show();
			messageManager.removeMessage(messages.get(position).id, new NListener<BaseData>() {

				@Override
				public void onResponse(BaseData data) {
					loadingDialog.dismiss();
					showToast(data.msg);
					if (data.status == Constant.STATUS_OK) {
						messages.remove(tempPosition);
						adapter.notifyDataSetChanged();
					}
				}

				@Override
				public void onErrResponse(VolleyError error) {
					loadingDialog.dismiss();
					showToast(error.getMessage());
				}

				@Override
				public void onAllPageLoaded(int nowPage, int totalPage) {

				}
			});
			break;

		case ANNOUNCEMENTS:
			loadingDialog.dismiss();
			announcementManager.removeAnnouncment(announcements.get(tempPosition).id, new NListener<BaseData>() {

				@Override
				public void onResponse(BaseData data) {
					loadingDialog.dismiss();
					showToast(data.msg);
					if (data.status == Constant.STATUS_OK) {
						announcements.remove(tempPosition);
						adapter.notifyDataSetChanged();
					}
				}

				@Override
				public void onErrResponse(VolleyError error) {
					loadingDialog.dismiss();
				}

				@Override
				public void onAllPageLoaded(int nowPage, int totalPage) {

				}
			});
			break;
		}
		adapter.notifyDataSetChanged();
		return false;
	}

}
